package birthday.syj.com.manage.common.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.litepal.crud.DataSupport;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import birthday.syj.com.manage.DB.MyFriends;
import birthday.syj.com.manage.R;
import birthday.syj.com.manage.common.showStarInfo.ShowMonthInfo;
import birthday.syj.com.manage.common.showStarInfo.ShowStarFuture;
import birthday.syj.com.manage.common.showStarInfo.ShowTomorrowInfo;
import birthday.syj.com.manage.common.showStarInfo.ShowWeekInfo;
import birthday.syj.com.manage.common.showStarInfo.ShowYearInfo;
import birthday.syj.com.manage.entity.ResponseHead;
import birthday.syj.com.manage.network.RetrofitHelper;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class FriendsInfo extends AppCompatActivity implements View.OnClickListener {

    public final static int NAME = 2;
    private int activityName;
    private int friendsId;
    private List<MyFriends> myFriendsList;

    TextView tvTime;//年龄，星座
    TextView tvTips;//生日距离提醒
    TextView tvBirthday;
    TextView tvName;//姓名和关系
    TextView tvPhone;//联系方式
    TextView tvRemindDate;//请设置提醒日期
    TextView tvRemindType;//请设置提醒方式
//    TextView tvRemark;//备注
    ImageView sexImage;
    TextView tvTodayStar;
    TextView tvTomorrowStar;
    TextView tvWeekStar;
    TextView tvMonthStar;
    TextView tvYearStar;
    TextView tvSee;
    TextView namebirth;


    //进度弹出框
    private ProgressDialog progressDialog;

    Calendar calendar = Calendar.getInstance();
    ResponseHead head;

    String constellation;
    String daysDivider;
    String birthDate;
    int id;
    int getId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friends_info);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        //控件初始化
        tvTime = (TextView) findViewById(R.id.tvTime);
        tvTips = (TextView) findViewById(R.id.tvTips);
        tvBirthday = (TextView) findViewById(R.id.tvBirthday);
        tvName = (TextView) findViewById(R.id.tvName);
        tvPhone = (TextView) findViewById(R.id.tvPhone);
        tvRemindDate = (TextView) findViewById(R.id.tvRemindDate);
        tvRemindType = (TextView) findViewById(R.id.tvRemindType);


        tvTodayStar = (TextView) findViewById(R.id.tvTodayStarSign);
        tvTomorrowStar = (TextView) findViewById(R.id.tvTomorrowStarSign);
        tvWeekStar = (TextView) findViewById(R.id.tvWeekStarSign);
        tvMonthStar = (TextView) findViewById(R.id.tvMonthStarSign);
        tvYearStar = (TextView) findViewById(R.id.tvYearStarSign);
        tvSee = (TextView) findViewById(R.id.tvSee);

        sexImage = (ImageView) findViewById(R.id.showSexIcon);


        namebirth = (TextView) findViewById(R.id.namebirth);

        //添加toolbar支持
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        Intent intent = getIntent();
        getId = intent.getIntExtra("id", 1);
        //判断是哪个intent跳转过来的
        activityName = intent.getIntExtra("ActivityName", 0);
        if (activityName == MainActivity.NAME) {
            //
            final MyFriends myFriends = DataSupport.find(MyFriends.class, getId);
            Log.e("test", myFriends.getDate());
            //判断星座
            int getMonth = myFriends.getBirthMonth();
            int getDay = myFriends.getBirthDay();
            getConstellation(getMonth, getDay);
            //填入已有的数据
            namebirth.setText(myFriends.getName());
            tvBirthday.setText(myFriends.getDate());
            tvPhone.setText(myFriends.getTelephone());
            tvName.setText(myFriends.getName()+"("+myFriends.getRelation()+")");
            tvRemindDate.setText(myFriends.getRemindDate());
            tvRemindType.setText(myFriends.getRemindType());
            friendsId = myFriends.getId();
            int getYear = myFriends.getBirthYear();
            int age = calendar.get(Calendar.YEAR) - getYear;
            Log.e("age", String.valueOf(age));
            tvTime.setText(age+"岁");
            tvSee.setText(constellation);
            tvTime.setTextSize(20);

            if (myFriends.getSex().equals("男")) {
                tvTime.setTextColor(getResources().getColor(R.color.blue));
                sexImage.setImageResource(R.mipmap.ic_male);
            } else {
                // TODO: 2017/12/23  
                tvTime.setTextColor(getResources().getColor(R.color.colorAccent));
                sexImage.setImageResource(R.mipmap.ic_famale);
            }
            birthDate = myFriends.getBirthYear()+"-"+myFriends.getBirthMonth()+"-"+myFriends.getBirthDay();
            getBirthday(birthDate);
            TextView getDivider = (TextView) findViewById(R.id.getDayDis);
            getDivider.setText(daysDivider+"天"+"");
            getDivider.setTextColor(getResources().getColor(R.color.colorAccent));
            tvTips.setText(getYear(myFriends.getBirthYear()));

            tvTodayStar.setOnClickListener(this);
            tvTomorrowStar.setOnClickListener(this);
            tvWeekStar.setOnClickListener(this);
            tvMonthStar.setOnClickListener(this);
            tvYearStar.setOnClickListener(this);

            showProgressDialog();
            getStarTodayInfo();
        }
    }

    //计算星座
    private void getConstellation(int month, int day) {
        String[] astro = new String[]{"摩羯座", "水瓶座", "双鱼座", "白羊座", "金牛座",
                "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座", "摩羯座"};
        int[] arr = new int[]{20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22};// 两个星座分割日
        int index = month;
        // 所查询日期在分割日之前，索引-1，否则不变
        if (day < arr[month - 1]) {
            index = index - 1;
        }
        constellation = astro[index];
    }

    /**
     * by syj
     * 计算生肖
     * @param year
     * @return
     */
    public String getYear(Integer year){
        if(year<1900){
            return "未知";
        }
        Integer start=1900;
        String [] years=new String[]{
                "鼠","牛","虎","兔",
                "龙","蛇","马","羊",
                "猴","鸡","狗","猪"
        };
        return years[(year-start)%years.length];
    }

    /**
     * by syj
     * 获取两个日期之间的间隔天数
     * @return
     */
    public void getBirthday(String getBirthDate) {
        String birthday = getBirthDate;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        int yearNow = cal.get(Calendar.YEAR);// 获得当前年份
        try {
            Log.i("Birthday_time", formatter.parse(birthday) + "");
            cal.setTime(formatter.parse(birthday));
        } catch (Exception e) {
            e.printStackTrace();
        }
        int birthyear = cal.get(Calendar.YEAR);
        Log.i("Birthday_year", birthyear + "");
        while (birthyear < yearNow) {
            cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) + 1);
            birthyear = cal.get(Calendar.YEAR);
            Log.i("Birthday_year++", birthyear + "");
        }
        Date ed = new Date();
        Log.i("Date_ed", ed + "");
        Date sd = cal.getTime();
        Log.i("Date_sd", ed + "");
        String days;
        if ((ed.getTime() - sd.getTime()) / (3600 * 24 * 1000) <= 0) {//>
            days = String.valueOf(-((ed.getTime() - sd.getTime()) / (3600 * 24 * 1000)) + 1);
            if (days.length()<=1){
                daysDivider = "0" + days;
            }else {
                daysDivider = days;
            }
        } else {
            cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) + 1);
            sd = cal.getTime();
            days = String.valueOf(-((ed.getTime() - sd.getTime()) / (3600 * 24 * 1000)) + 1);
            if (days.length()<=1){
                daysDivider = "0" + days;
            }else {
                daysDivider = days;
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.edit_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            case R.id.edit:
                Intent intent = new Intent(this, AddBirthDay.class);
                Bundle bundle = new Bundle();
                bundle.putInt("ActivityName", NAME);
                Log.e("这次的ACtivityName的值是:", String.valueOf(NAME));
                bundle.putInt("getId", getId);
                intent.putExtras(bundle);
                startActivity(intent);
            default:
                break;
        }
        return true;
    }

    private void getStarTodayInfo() {

        //获取星座id
        if (constellation.equals("白羊座")) {
            id = 1;
        }

        if (constellation.equals("金牛座")) {
            id = 2;
        }

        if (constellation.equals("双子座")) {
            id = 3;
        }

        if (constellation.equals("巨蟹座")) {
            id = 4;
        }

        if (constellation.equals("狮子座")) {
            id = 5;
        }

        if (constellation.equals("处女座")) {
            id = 6;
        }

        if (constellation.equals("天秤座")) {
            id = 7;
        }

        if (constellation.equals("天蝎座")) {
            id = 8;
        }

        if (constellation.equals("射手座")) {
            id = 9;
        }

        if (constellation.equals("摩羯座")) {
            id = 10;
        }

        if (constellation.equals("水瓶座")) {
            id = 11;
        }

        if (constellation.equals("双鱼座")) {
            id = 12;
        }
        RetrofitHelper.getBirthService()
                .getAstro(id, birthDate)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseHead>() {
                    @Override
                    public void onCompleted() {
                        closeProgressDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        closeProgressDialog();
                        Toast.makeText(FriendsInfo.this, "请检查网络连接！", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(ResponseHead responseHead) {
                        head = responseHead;
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvTodayStarSign:
                Bundle bundle = new Bundle();
                //传送当日数据
                String getAstroname = head.getResult().getAstroname();
                String getDate = head.getResult().getToday().getDate();
                String getPresummary = head.getResult().getToday().getPresummary();
                String getSummary = head.getResult().getToday().getSummary();
                String getLove = head.getResult().getToday().getLove();
                String getMoney = head.getResult().getToday().getMoney();
                String getCareer = head.getResult().getToday().getCareer();
                String getStar = head.getResult().getToday().getStar();
                String getColor = head.getResult().getToday().getColor();
                String getNumber = head.getResult().getToday().getNumber();
                String getHealth = head.getResult().getToday().getHealth();

                Intent intent = new Intent(FriendsInfo.this, ShowStarFuture.class);
                bundle.putString("getAstroname", getAstroname);
                bundle.putString("getDate", getDate);
                bundle.putString("getPresummary", getPresummary);
                bundle.putString("getSummary", getSummary);
                bundle.putString("getLove", getLove);
                bundle.putString("getMoney", getMoney);
                bundle.putString("getCareer", getCareer);
                bundle.putString("getStar", getStar);
                bundle.putString("getColor", getColor);
                bundle.putString("getNumber", getNumber);
                bundle.putString("getHealth", getHealth);
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            case R.id.tvTomorrowStarSign:
                Bundle bundle1 = new Bundle();
                //传送明日数据
                String getTomorrowDate = head.getResult().getTomorrow().getDate();
                String getTomorrowPresummary = head.getResult().getTomorrow().getPresummary();
                String getTomorrowSummary = head.getResult().getTomorrow().getSummary();
                String getTomorrowLove = head.getResult().getTomorrow().getLove();
                String getTomorrowMoney = head.getResult().getTomorrow().getMoney();
                String getTomorrowCareer = head.getResult().getTomorrow().getCareer();
                String getTomorrowStar = head.getResult().getTomorrow().getStar();
                String getTomorrowColor = head.getResult().getTomorrow().getColor();
                String getTomorrowNumber = head.getResult().getTomorrow().getNumber();
                String getTomorrowHealth = head.getResult().getTomorrow().getHealth();

                Intent intent1 = new Intent(FriendsInfo.this, ShowTomorrowInfo.class);
                bundle1.putString("getTomorrowDate", getTomorrowDate);
                bundle1.putString("getTomorrowPresummary", getTomorrowPresummary);
                bundle1.putString("getTomorrowSummary", getTomorrowSummary);
                bundle1.putString("getTomorrowLove", getTomorrowLove);
                bundle1.putString("getTomorrowMoney", getTomorrowMoney);
                bundle1.putString("getTomorrowCareer", getTomorrowCareer);
                bundle1.putString("getTomorrowStar", getTomorrowStar);
                bundle1.putString("getTomorrowColor", getTomorrowColor);
                bundle1.putString("getTomorrowNumber", getTomorrowNumber);
                bundle1.putString("getTomorrowHealth", getTomorrowHealth);
                intent1.putExtras(bundle1);
                startActivity(intent1);
                break;
            case R.id.tvWeekStarSign:
                Bundle bundle2 = new Bundle();
                //传递一周数据
                String getWeekDate = head.getResult().getWeek().getDate();
                String getWeekLove = head.getResult().getWeek().getLove();
                String getWeekCareer = head.getResult().getWeek().getCareer();
                String getWeekJob = head.getResult().getWeek().getJob();
                String getWeekMoney = head.getResult().getWeek().getMoney();
                String getWeekHealth = head.getResult().getWeek().getHealth();

                Intent intent2 = new Intent(FriendsInfo.this, ShowWeekInfo.class);
                bundle2.putString("getWeekDate", getWeekDate);
                bundle2.putString("getWeekLove", getWeekLove);
                bundle2.putString("getWeekCareer", getWeekCareer);
                bundle2.putString("getWeekJob", getWeekJob);
                bundle2.putString("getWeekMoney", getWeekMoney);
                bundle2.putString("getWeekHealth", getWeekHealth);
                intent2.putExtras(bundle2);
                startActivity(intent2);
                break;
            case R.id.tvMonthStarSign:
                Bundle bundle3 = new Bundle();
                //获取一个月的运势
                String getMonthSummary = head.getResult().getMonth().getSummary();
                String getMonthLove = head.getResult().getMonth().getLove();
                String getMonthCareer = head.getResult().getMonth().getCareer();
                String getMonthHealth = head.getResult().getMonth().getHealth();
                String getMonthMoney = head.getResult().getMonth().getMoney();
                String getMonthDate = head.getResult().getMonth().getDate();

                Intent intent3 = new Intent(FriendsInfo.this, ShowMonthInfo.class);
                bundle3.putString("getMonthSummary", getMonthSummary);
                bundle3.putString("getMonthLove", getMonthLove);
                bundle3.putString("getMonthCareer", getMonthCareer);
                bundle3.putString("getMonthHealth", getMonthHealth);
                bundle3.putString("getMonthMoney", getMonthMoney);
                bundle3.putString("getMonthDate", getMonthDate);
                intent3.putExtras(bundle3);
                startActivity(intent3);
                break;
            case R.id.tvYearStarSign:
                Bundle bundle4 = new Bundle();
                //获取一年的运势
                String getYearDate = head.getResult().getYear().getDate();
                String getYearSummary = head.getResult().getYear().getSummary();
                String getYearMoney = head.getResult().getYear().getMoney();
                String getYearCareer = head.getResult().getYear().getCareer();
                String getYearLove = head.getResult().getYear().getLove();

                Intent intent4 = new Intent(FriendsInfo.this, ShowYearInfo.class);
                bundle4.putString("getYearDate", getYearDate);
                bundle4.putString("getYearSummary", getYearSummary);
                bundle4.putString("getYearMoney", getYearMoney);
                bundle4.putString("getYearCareer", getYearCareer);
                bundle4.putString("getYearLove", getYearLove);
                intent4.putExtras(bundle4);
                startActivity(intent4);
                break;
            default:
                break;
        }
    }

    /**
     * 显示进度对话框
     */
    private void showProgressDialog(){
        if(progressDialog==null){
            progressDialog=new ProgressDialog(this);
            progressDialog.setMessage("正在加载中，请稍等");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }
    /**
     * 关闭进度对话框
     */
    private void closeProgressDialog(){
        if(progressDialog!=null){
            progressDialog.dismiss();
        }
    }
}
